/*
 * @Author: Turump 
 * @Date: 2021-03-30 09:38:46 
 * @Last Modified by: Turump
 * @Last Modified time: 2021-03-31 16:36:15
 */
const { ccclass, property } = cc._decorator;

@ccclass("EventListener")
export default class EventListener {
    @property({ override: true, tooltip: "事件名称" })
    eventName: string = '';

    @property(cc.Component.EventHandler)
    eventHander: cc.Component.EventHandler = new cc.Component.EventHandler();

    @property()
    isEnable: boolean = true;

    @property({ tooltip: "是否中断其它监听" })
    isSwallow: boolean = false;

    //param com: cc.Component, handerName: string, eventName: string
    constructor(...params: any) {
        let com = params[0];
        let handerName = params[1];
        let eventName = params[2];
        if (com != null && handerName != null) {
            this.eventHander.target = com.node;

            var className = cc.js.getClassName(com);
            var trimLeft = className.lastIndexOf('.');
            if (trimLeft >= 0) {
                className = className.slice(trimLeft + 1);
            }
            this.eventHander.component = className;

            this.eventHander.handler = handerName;
        }
        if (eventName != null) {
            this.eventName = eventName;
        }
    }

    static emitEvents(_eventName: string, events: EventListener[], ...params: any[]): void {
        for (let e of events) {
            if (e.emit(_eventName, ...params)) {
                break;
            }
        }
    }

    emit(_eventName: string, ...params: any[]): boolean {
        if (_eventName == "") {
            return;
        }
        if (_eventName != this.eventName) {
            return false;
        }
        if (!this.isEnable) {
            return false;
        }
        if (this.eventHander == null) {
            return false;
        }

        let tempParams = params.slice();
        tempParams.push(this);
        this.eventHander.emit(tempParams);
        return this.isSwallow;
    }

}